const mongoose = require('utils/mongoose.js');

const constant = require('utils/constant.js');
const log = require('log4js').getLogger('ActivityModel');

const ActivitySchema = new mongoose.Schema({
	name			: String, 	// 活动名
	state			: Number, 	// 状态： 0 默认 1 进行中 2 结束
	create_time 	: Number,
	start_time	 	: Number,
	end_time		: Number,
	module_name 	: String, 	// 逻辑模块名字
	has_web			: Boolean,	// 是否有web接口需要挂载
}); 

ActivitySchema.methods.registerStateChangeNotify = function(callback) {
	this.callback = callback;
};

ActivitySchema.methods.checkState = function() {

	log.info('activity[' + this.name + '] check state! state : ' + this.state);

	let nowTime = Date.now();
	let newState = this.state;
	let startTime = this.start_time;
	let endTime = this.end_time;
	let needTimer = true;
	let delayTime = 0;
	let that = this;

	if(nowTime >= endTime) {
		newState = 2;
		needTimer = false;
	} else if (nowTime < startTime) {
		newState = 0;
		delayTime = startTime - nowTime;
	} else {
		newState = 1;
		delayTime = endTime - nowTime;
	}
	log.info(delayTime);
	//定时器
	if(needTimer) {

		if(delayTime > constant.setTimeoutMaxValue){
			delayTime = 24 * 3600 * 1000 ; // 1 day
		} else {
			//矫正逻辑偏移时间
			delayTime += Date.now() - nowTime;
		}

		setTimeout(function() {
			that.checkState();
		}, delayTime);
	}

	if(newState != this.state) {
		
		let oldState = this.state;


		this.state = newState;

		this.save(function(err, doc) {
			if(err) {
				log.info('activity[' + that.name + '] update state to db error, msg : ' + err);
			} else {
				log.info('activity[' + that.name + '] update state to db success ' + doc);
			}
		});


		if(typeof this.callback != 'undefined') {
			this.callback(this, oldState, newState);
		}
	}
}

module.exports = mongoose.model('Activity', ActivitySchema);